//
//  WYZfbPay.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/16.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "WYZfbPay.h"
#import "Order.h"
#import "DataSigner.h"
#import "APAuthV2Info.h"
#import "PayedVC.h"
#import "WYMainTabBarVC.h"
#import <Foundation/Foundation.h>
//回调地址
#define NOTIFY_URL @"/api/ApiPay/notify"
#define DEL_ORDER_URL @"/api/ApiPay/cancelCartOrdersForPay"
#define DEL_CHONGZHI_URL @"/api/ApiPay/cancelRechargeOrdersForPay"
@interface WYZfbPay ()
{
    //记录订单编号
    NSString *_orderId;
}
@end
@implementation WYZfbPay
//付款
-(void)zfbPayWithOrderNum:(NSString *)OrderNum OrderId:(NSString *)orderid PdcTitle:(NSString *)pdcTitle PdcDesc:(NSString *)desc Price:(NSString *)price
{
    //记录订单编号
    _orderId = orderid;
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
//    NSString *partner = @"2088911921764370";
//    NSString *seller = @"xiaocai@dbba.cn";
//    NSString *privateKey = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMq6eBFUMXwzcIXFhejCXuaTO0TmjfiM/Ud0mXkLrDvP1pLlWyutusuWOUshjgs/AWk89bCKAtMy9qSEHl2ZqNHmP83TNpOL3NttEkSpHGl/ZbhEiqaHZj/sJgdwutQh3dlfqrR7DXriP+okfCJ/5I9hg1Qv9tr4ywCb/DusVEEJAgMBAAECgYEAyDkIktzbjvZjAMvH6M3n2sS5OeCXgU8GbAdd+K4tqlkobKa3t9j6703sQibe2n6czyqU4Yo9JghkjrGqJ/m2P+2y6jQgI83pvM1t87NtTRo6PXNxhKz6J74ufzAqL+VqvQoSZyPZMy2iBbZ7iY9YimZNvg1p+Db58mGJrXUUfrECQQDzZT7X/Ed+LM8Qb00ddPycMdOyWlb+oKKAwZ6wLdEE0S00LAYxcqyPRNWQYi/bzhd0SdF9Pq4XY9z+2dYGhQEFAkEA1ToW+PC5n+WMuBk/MrVXVY/xykeZAXUrev12DOn0xR4o+hgf+6YdB9+HKbN0tTyPjw/Mht+X0WVkvXV9PJjPNQJAZ0SHu2AAfVpJqHFwyJTAMQ07Aqstye8hw3ti9uEZk++kPESJhCVhbZAJBK+EGsCAVwiS547Wknn+Y+rM0gtQeQJBALupH3TC8KvgbKPOXIe1gAKm6Ed+EhRtWfIpxs8AzVL7A1dxCh0BisVWHnA+J7YmcbaYUgpWGRjKown3sFw3pQ0CQFhvNPyRU7tha+cZeT4yrTkE+M9pRafs6fq0wMiwIT/89MOV0/pCTCKR0gzjaQi0LVQcImgRA702U1OI74O+saA=";
    NSString *partner = self.payModel.partner;
    NSString *seller  = self.payModel.seller;
    NSString *privateKey = self.payModel.private_key;
    /*============================================================================*/
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }

    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = OrderNum; //订单ID(由商家□自□行制定)
    order.productName = pdcTitle; //商品标题
    order.productDescription = desc; //商品描述
    order.amount = price; //商 品价格
    NSString *parstr = [NSString stringWithFormat:@"%@%@/alipay_mobile",DBB_IP,NOTIFY_URL];
    order.notifyURL = [parstr stringByReplacingOccurrencesOfString:@"?" withString:@"index.php"]; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemodbb";
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description]; 
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循 RSA 签名规范, 并将签名字符串 base64 编码和 UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            NSString *rlt = resultDic[@"resultStatus"];
            if ([rlt isEqualToString:@"9000"]) {/*******************支付成功******************/
                if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
                    //跳往支付结果界面刷新结果
                    PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
                    if(self.isChongZhiFlag){
                        payedVC.rltType = ChongZhiSuccess;
                    }else{
                        payedVC.rltType = PdcSuccess;
                    }
                    [payedVC updateViews];
                }
            }else{/*****************支付失败**********************/
                //取消订单
                if (self.isChongZhiFlag) {
                    [self cancelChangzhiOrder];
                }else{
                    [self cancelOrder];
                }
                //跳往支付结果界面
                if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
                    //跳往支付结果界面刷新结果
                    PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
                    if(self.isChongZhiFlag){
                        payedVC.rltType = ChongZhiFailed;
                    }else{
                        payedVC.rltType = PdcFailed;
                    }
                    [payedVC updateViews];
                }
            }
        }];
    }
    
}
//取消订单
-(void)cancelOrder
{
    //取消订单
    NSDictionary *params = @{@"ids":_orderId,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DEL_ORDER_URL] Parameters:params successBlock:^(NSDictionary *dic) {
//        NSLog(@"取消订单成功！");
    } failedBlock:^{
    } needLog:NO];
    
}
//取消充值订单
- (void)cancelChangzhiOrder
{
    //取消订单
    NSDictionary *params = @{@"ids":_orderId,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DEL_CHONGZHI_URL] Parameters:params successBlock:^(NSDictionary *dic) {
//        NSLog(@"取消订单成功！");
    } failedBlock:^{
    } needLog:NO];
}
@end
